package com.sc.filter;

import com.sc.token.TokenValidationResult;
import com.sc.token.TokenProperties;
import com.sc.token.TokenTemplate;
import com.sc.utils.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 实现全局过滤器，自定义token拦截器,当前不完善，不能动态修改
 */
@Component
public class TokenFilter implements Ordered, GlobalFilter {
    @Autowired
    TokenTemplate tokenTemplate;
    @Autowired
    TokenProperties tokenProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取http请求实例
        ServerHttpRequest request = exchange.getRequest();
        //获取所有请求头
        HttpHeaders httpHead = request.getHeaders();
        //获取响应对象
        ServerHttpResponse httpResponse = exchange.getResponse();

        // 跳过不需要验证的路径
        String url = request.getURI().getPath();
//        if (StringUtils.matches(url, tokenProperties.getExcludePatterns()))
//        {
//            return chain.filter(exchange);
//        }
        //判断url中是否含有某个路径
        for (String path: tokenProperties.getExcludePatterns()) {
            if(url.indexOf(path) > 0){
                return chain.filter(exchange);
            }
        }
        //从请求头中获取token
        String token = httpHead.getFirst("x-token");
        //验证token的逻辑
        if (null == token){
            //没有携带token，不能进行访问,返回无权访问的提示信息

            //将信息写入响应
            return httpResponse.writeWith(Mono.just(error(httpResponse,"无权访问")));
        }
        //判断token是否正确
        TokenValidationResult tokenResult = tokenTemplate.validationToken(token);
        if(tokenResult.getCode() == 0){
            //token错误，返回错误信息
            return httpResponse.writeWith(Mono.just(error(httpResponse,tokenResult.getMsg())));
        }
        //放行该过滤器
        return chain.filter(exchange);
    }

    /**
     * 过滤器级别，数字越小，级别越高
     */
    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * token错误，将错误信息写入响应
     * @param response 响应对象
     * @param msg      token错误信息
     */
    DataBuffer error(ServerHttpResponse response,String msg){
        //设置响应的格式和编码
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");

        //设置响应状态码(未授权状态)
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //将错误信息封装为json格式，写入响应
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg",msg);

        return response.bufferFactory().wrap(jsonObject.toString().getBytes());
    }
}

